import { Byte } from '../../api/io/Byte';
import { AdminMailDrop } from './AdminMailDrop';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';
import { MathUtils } from '../../api/math/MathUtils';



/**运营后台发的邮件属性枚举*/
export const enum E_AdminMail {
	/**后台的邮件Id*/
	MAIL_ID = 0,
	/**邮件标题*/
	TITLE = 1,
	/**邮件正文*/
	BODY = 2,
	/**接收邮件的玩家ID,all表示所有,多个玩家用英文分号;分割*/
	PLAYER_IDS = 3,
	/**定时发送时间*/
	START_TIME = 4,
	/**有效时间，0-无限制*/
	VALID_TIME = 5,
	/**邮件奖励*/
	DROPS = 6,
	/**枚举数量*/
	EnumCount = 7
}


/**运营后台发的邮件*/
export class AdminMail {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_ADMIN_MAIL_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_ADMIN_MAIL_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: AdminMail[] = [];

	/**创建入口*/
	public static create(json?: string): AdminMail {
		const c = this.POOL.pop() || new AdminMail();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**后台的邮件Id (uint32)*/
	protected _mailId: number;
	/**邮件标题*/
	protected _title: string;
	/**邮件正文*/
	protected _body: string;
	/**接收邮件的玩家ID,all表示所有,多个玩家用英文分号;分割*/
	protected _playerIds: string;
	/**定时发送时间 (long)*/
	protected _startTime: number;
	/**有效时间，0-无限制 (long)*/
	protected _validTime: number;
	/**邮件奖励*/
	protected _drops: AdminMailDrop[] = [];


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (AdminMail.POOL.indexOf(this) === -1) {
			AdminMail.POOL.push(this);
		}
	}

	/**后台的邮件Id*/
	public get mailId() {
		return this._mailId;
	}


	/**后台的邮件Id*/
	public set mailId(v: number) {
		this._mailId = v;
	}


	/**邮件标题*/
	public get title() {
		return this._title;
	}


	/**邮件标题*/
	public set title(v: string) {
		this._title = v;
	}


	/**邮件正文*/
	public get body() {
		return this._body;
	}


	/**邮件正文*/
	public set body(v: string) {
		this._body = v;
	}


	/**接收邮件的玩家ID,all表示所有,多个玩家用英文分号;分割*/
	public get playerIds() {
		return this._playerIds;
	}


	/**接收邮件的玩家ID,all表示所有,多个玩家用英文分号;分割*/
	public set playerIds(v: string) {
		this._playerIds = v;
	}


	/**定时发送时间*/
	public get startTime() {
		return this._startTime;
	}


	/**定时发送时间*/
	public set startTime(v: number) {
		this._startTime = v;
	}


	/**有效时间，0-无限制*/
	public get validTime() {
		return this._validTime;
	}


	/**有效时间，0-无限制*/
	public set validTime(v: number) {
		this._validTime = v;
	}


	/**增加邮件奖励*/
	public addDrops(v: AdminMailDrop): void {
		if (this._drops.indexOf(v) === -1) {
			this._drops.push(v);
		}
	}

	/**删除邮件奖励*/
	public removeDrops(v: AdminMailDrop): void {
		const idx = this._drops.indexOf(v);
		if (idx >= 0) {
			this._drops.splice(idx, 1);
		}
	}

	/**获取邮件奖励列表*/
	public getDropsList(): AdminMailDrop[] {
		return this._drops;
	}


	/**通过枚举获取值*/
	public getV(k: E_AdminMail): any {
		switch (k) {
			case E_AdminMail.MAIL_ID: return this._mailId;
			case E_AdminMail.TITLE: return this._title;
			case E_AdminMail.BODY: return this._body;
			case E_AdminMail.PLAYER_IDS: return this._playerIds;
			case E_AdminMail.START_TIME: return this._startTime;
			case E_AdminMail.VALID_TIME: return this._validTime;
			case E_AdminMail.DROPS: return this._drops;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_AdminMail, v: any): void {
		switch (k) {
			case E_AdminMail.MAIL_ID: this._mailId = v; break;
			case E_AdminMail.TITLE: this._title = v; break;
			case E_AdminMail.BODY: this._body = v; break;
			case E_AdminMail.PLAYER_IDS: this._playerIds = v; break;
			case E_AdminMail.START_TIME: this._startTime = v; break;
			case E_AdminMail.VALID_TIME: this._validTime = v; break;
			case E_AdminMail.DROPS: this._drops = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//后台的邮件Id
		this._mailId = 0;
		//邮件标题
		this._title = '';
		//邮件正文
		this._body = '';
		//接收邮件的玩家ID,all表示所有,多个玩家用英文分号;分割
		this._playerIds = '';
		//定时发送时间
		this._startTime = 0;
		//有效时间，0-无限制
		this._validTime = 0;
		//邮件奖励
		if (this._drops) {
			const list = this._drops;
			for (let i = 0, len = list.length; i < len; i++) {
				list[i].destroy();
			}
			this._drops.length = 0;
		}
		else {
			this._drops = [];
		}
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._mailId) {
			json.mailId = this._mailId;
		}
		if (this._title) {
			json.title = this._title;
		}
		if (this._body) {
			json.body = this._body;
		}
		if (this._playerIds) {
			json.playerIds = this._playerIds;
		}
		if (this._startTime) {
			json.startTime = this._startTime;
		}
		if (this._validTime) {
			json.validTime = this._validTime;
		}
		if (this._drops) {
			const list: string[] = [];
			const vs = this._drops;
			for (let i = 0, len = vs.length; i < len; i++) {
				list[i] = vs[i].stringify(false);
			}
			json.drops = list;
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.mailId) {
			this._mailId = json.mailId;
		}
		if (json.title) {
			this._title = json.title;
		}
		if (json.body) {
			this._body = json.body;
		}
		if (json.playerIds) {
			this._playerIds = json.playerIds;
		}
		if (json.startTime) {
			this._startTime = json.startTime;
		}
		if (json.validTime) {
			this._validTime = json.validTime;
		}
		if (json.drops) {
			const list = json.drops;
			for (let i = 0, len = list.length; i < len; i++) {
				this._drops.push(AdminMailDrop.create(list[i]));
			}
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		byte.writeUint32(this._mailId);
		byte.writeString(this._title);
		byte.writeString(this._body);
		byte.writeString(this._playerIds);
		byte.writeLongNumber(this._startTime);
		byte.writeLongNumber(this._validTime);
		//邮件奖励
		{
			const list = this._drops;
			if (list) {
				byte.writeUint32(list.length);
				for (let i = 0, len = list.length; i < len; i++) {
					list[i].toBytes(byte);
				}
			}
			else {
				byte.writeUint32(0);
			}
		}
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		this._mailId = byte.readUint32();
		this._title = byte.readString();
		this._body = byte.readString();
		this._playerIds = byte.readString();
		this._startTime = byte.readLongNumber();
		this._validTime = byte.readLongNumber();
		//邮件奖励
		{
			const len = byte.readUint32();
			for (let i = 0; i < len; i++) {
				const cv = AdminMailDrop.create();
				cv.fromBytes(byte);
				this._drops[i] = cv;
			}
		}
		return this;
	}


	/**克隆*/
	public clone(): AdminMail {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = AdminMail.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = AdminMail.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			//后台的邮件Id
			if (idx === E_AdminMail.MAIL_ID) {
				const oldv = this._mailId;
				this._mailId = us[i + 1];
				IAsync.dispatch(eventID, idx, this._mailId, oldv);
				i += 2;
				continue;
			}
			//邮件标题
			if (idx === E_AdminMail.TITLE) {
				const oldv = this._title;
				this._title = us[i + 1];
				IAsync.dispatch(eventID, idx, this._title, oldv);
				i += 2;
				continue;
			}
			//邮件正文
			if (idx === E_AdminMail.BODY) {
				const oldv = this._body;
				this._body = us[i + 1];
				IAsync.dispatch(eventID, idx, this._body, oldv);
				i += 2;
				continue;
			}
			//接收邮件的玩家ID,all表示所有,多个玩家用英文分号;分割
			if (idx === E_AdminMail.PLAYER_IDS) {
				const oldv = this._playerIds;
				this._playerIds = us[i + 1];
				IAsync.dispatch(eventID, idx, this._playerIds, oldv);
				i += 2;
				continue;
			}
			//定时发送时间
			if (idx === E_AdminMail.START_TIME) {
				const oldv = this._startTime;
				this._startTime = us[i + 1];
				IAsync.dispatch(eventID, idx, this._startTime, oldv);
				i += 2;
				continue;
			}
			//有效时间，0-无限制
			if (idx === E_AdminMail.VALID_TIME) {
				const oldv = this._validTime;
				this._validTime = us[i + 1];
				IAsync.dispatch(eventID, idx, this._validTime, oldv);
				i += 2;
				continue;
			}
			//邮件奖励
			if (idx === E_AdminMail.DROPS) {
				const c: number = us[i + 1];
				const v = AdminMailDrop.create(us[i + 2]);
				IAsync.dispatch(eventID, idx, c, v);
				i += 3;
				continue;
			}

			console.error('[Struct Data] can not find enum in AdminMail with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: AdminMail): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];

		if (this._mailId !== other._mailId) {
			updates.push(E_AdminMail.MAIL_ID, this._mailId);
		}
		if (this._title !== other._title) {
			updates.push(E_AdminMail.TITLE, this._title);
		}
		if (this._body !== other._body) {
			updates.push(E_AdminMail.BODY, this._body);
		}
		if (this._playerIds !== other._playerIds) {
			updates.push(E_AdminMail.PLAYER_IDS, this._playerIds);
		}
		if (this._startTime !== other._startTime) {
			updates.push(E_AdminMail.START_TIME, this._startTime);
		}
		if (this._validTime !== other._validTime) {
			updates.push(E_AdminMail.VALID_TIME, this._validTime);
		}

		//邮件奖励
		{
			const idx = E_AdminMail.DROPS;
			const rs = MathUtils.intersectSortedArray(this._drops, other._drops);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const newv = list[i];
					updates.push(idx, 1, newv.stringify(false));
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const newv = list[i];
					updates.push(idx, 1, newv.stringify(false));
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					const oldv = list[i];
					updates.push(idx, 0, oldv.getV(0));
				}
			}
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(AdminMail.TOTAL_EVENT_ID, this.getV(0));
	}

}
